#include "stdafx.h"
#include "Box2DSystem.h"
#include "EntityDataStore.h"

#include "PositionComponent.h"
#include "Box2DComponent.h"

namespace ZeEngine
{
    Box2DSystem::Box2DSystem(EntityDataStore& entityDataStore, b2World& world) : IComponentSystem(entityDataStore), m_world(world)
    {
        SetRequiredComponents(ePositionComponent | eBox2DComponent);
    }


    Box2DSystem::~Box2DSystem()
    {
    }

    bool Box2DSystem::Init()
    {
        m_world.SetGravity(b2Vec2(0, 15.0f));
        return true;
    }

    void Box2DSystem::Update(Uint32 deltaMS)
    {
        m_world.Step(1.0f / deltaMS, 8, 3);
    }

    void Box2DSystem::PostUpdate(Uint32 deltaMS)
    {
        for (auto it = m_entityDataStore.Begin(); it != m_entityDataStore.End(); ++it)
        {
            Entity* pEntity = it->second;

            if (pEntity && IsEntitySupported(pEntity))
            {   
                //Update position from box2d
                PositionComponent* pPositionComponent = pEntity->GetComponent<PositionComponent>(ePositionComponent);
                Box2DComponent* pBox2DComponent = pEntity->GetComponent<Box2DComponent>(eBox2DComponent);

                if (pPositionComponent && pBox2DComponent)
                {
                    b2Body* pBody = pBox2DComponent->m_pBody;

                    if (pBody)
                    {
                        pPositionComponent->SetPosition(Vector2D<float>(pBody->GetPosition()) * PTM_RATIO);
                        pPositionComponent->m_rotation = pBody->GetAngle();
                    }
                }           
            }
        }
    }
}
